package com.hy.mydesktop.server.rpc;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;

import net.sf.gilead.configuration.ConfigurationHelper;
import net.sf.gilead.core.PersistentBeanManager;
import net.sf.gilead.core.hibernate.jpa.HibernateJpaUtil;
import net.sf.gilead.core.serialization.GwtProxySerialization;
import net.sf.gilead.core.store.stateless.StatelessProxyStore;
import net.sf.gilead.gwt.PersistentRemoteService;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.hy.enterprise.framework.service.spring.MySpringUtil;

//public class BaseRpcServiceWithSpring extends RemoteServiceServlet{   
public class BaseRpcServiceWithSpring extends PersistentRemoteService{   
		protected	PersistentBeanManager beanManager = null;
		private	EntityManagerFactory entityManagerFactory =null;	
		private static final long serialVersionUID = 1L;   	
		protected WebApplicationContext springContext;   

        
		@Override    
        public void init(ServletConfig config) throws ServletException {     
    		System.err.println("%%%%% execute init(参数)");

        	super.init(config);     
//          springContext = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());  //读取配置文件  
            springContext = MySpringUtil.createWebApplicationContext(config.getServletContext());  //读取配置文件  
           
//            beanManager = springContext.getBean("persistentBeanManager", PersistentBeanManager.class);
            entityManagerFactory = springContext.getBean("entityManagerFactory", EntityManagerFactory.class);
    //  
			//对于PersistentBeanManager，  
			//需要使用GwtConfigurationHelper.initGwtStatelessBeanManager(gileadHibernateUtil)  
			//这句话进行配置，而不是简单的new  
			beanManager = ConfigurationHelper.initStatelessBeanManager(new HibernateJpaUtil(
					(EntityManagerFactory)springContext.getBean("entityManagerFactory")));
//			        下面注释掉的这句话不需要  
			 StatelessProxyStore  proxyStore = new StatelessProxyStore(); 
			 proxyStore.setProxySerializer(new GwtProxySerialization());
//				        下面注释掉的这句话不需要  
			 beanManager.setProxyStore(proxyStore);  
				      setBeanManager(beanManager);    
            // System.err.println("1111111111111111111111111LLL"+config.getServletContext());
           // System.err.println("1111111111111111111111111LLL"+springContext);
           
        }   
		
		public EntityManagerFactory getEntityManagerFactory() {
			return entityManagerFactory;
		}


		public PersistentBeanManager getBeanManager() {
			return beanManager;
		}
		
		public WebApplicationContext getSpringContext() {
				return springContext;
			}
      
}  
